﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Reflection;
using System.Data;
using System.Web;
using System.Configuration;

namespace SystemFrameWork
{
    public class PageHelper
    {
        /// <summary>
        /// Get control value from row
        /// The control must implement ITextControl interface
        /// </summary>
        /// <param name="row"></param>
        /// <param name="textboxID"></param>
        /// <returns></returns>
        public static string GetITextControlValueFromRow(GridViewRow row, string textboxID)
        {
            ITextControl txtControl = row.FindControl(textboxID) as ITextControl;
            if (txtControl != null)
            {
                return txtControl.Text;
            }
            return string.Empty;
        }

        /// <summary>
        /// Get control value from item
        /// </summary>
        /// <param name="item"></param>
        /// <param name="textboxID"></param>
        /// <returns></returns>
        ///add by ganxiaotu 2010-1-12
        public static string GetITextControlValueFromItem(DataListItem item, string textboxID)
        {
            ITextControl txtControl = item.FindControl(textboxID) as ITextControl;
            if (txtControl != null)
            {
                return txtControl.Text;
            }
            return string.Empty;
        }

        /// <summary>
        /// Set control value to row
        /// The control must implement ITextControl interface
        /// </summary>
        /// <param name="row"></param>
        /// <param name="textboxID"></param>
        /// <param name="value"></param>
        public static void SetITextControlValueToRow(GridViewRow row, string textboxID, string value)
        {
            ITextControl txtControl = row.FindControl(textboxID) as ITextControl;
            if (txtControl != null)
            {
                txtControl.Text = value;
            }
        }

        /// <summary>
        /// find a sub control in the grid view
        /// </summary>
        /// <param name="row"></param>
        /// <param name="controlID"></param>
        /// <returns></returns>
        public static object FindGridViewSubControlObj(GridViewRow row, string controlID)
        {
            return row.FindControl(controlID);
        }

        /// <summary>
        /// find a sub control in the grid view
        /// </summary>
        /// <param name="row"></param>
        /// <param name="controlID"></param>
        /// <returns></returns>
        public static object FindDataListSubControlObj(DataListItem item, string controlID)
        {
            return item.FindControl(controlID);
        }


        /// <summary>
        /// find a sub control in the UserControl
        /// </summary>
        /// <param name="row"></param>
        /// <param name="controlID"></param>
        /// <returns></returns>
        public static object FindUserControlSubControlObj(Control userControl, string controlID)
        {
            return userControl.FindControl(controlID);
        }



        /// <summary>
        /// Set control value to row
        /// The control must implement ITextControl interface
        /// </summary>
        /// <param name="row"></param>
        /// <param name="textboxID"></param>
        /// <param name="value"></param>
        public static void SetITextControlValueToRow(GridViewRow row, string textboxID, string value, bool readOnly)
        {
            ITextControl txtControl = row.FindControl(textboxID) as ITextControl;
            if (txtControl != null)
            {
                txtControl.Text = value;
                TextBox txt = txtControl as TextBox;
                if (txt != null)
                {
                    txt.ReadOnly = readOnly;
                }
            }
        }

        /// <summary>
        /// Get control value from DataListItem
        /// The control must implement ICheckControl interface
        /// </summary>
        /// <param name="row"></param>
        /// <param name="checkboxID"></param>
        /// <returns></returns>
        public static bool GetICheckControlValueFromRow(DataListItem item, string checkboxID)
        {
            ICheckBoxControl chkControl = item.FindControl(checkboxID) as ICheckBoxControl;
            if (chkControl != null)
            {
                return chkControl.Checked;
            }
            return false;
        }

        /// <summary>
        /// Set control value to DataListItem
        /// The control must implement ICheckControl interface
        /// </summary>
        /// <param name="row"></param>
        /// <param name="checkboxID"></param>
        /// <param name="value"></param>
        public static void SetICheckControlValueToRow(DataListItem item, string checkboxID, bool value)
        {
            ICheckBoxControl chkControl = item.FindControl(checkboxID) as ICheckBoxControl;
            if (chkControl != null)
            {
                chkControl.Checked = value;
            }
        }

        /// <summary>
        /// Get control value from row
        /// The control must implement ICheckControl interface
        /// </summary>
        /// <param name="row"></param>
        /// <param name="checkboxID"></param>
        /// <returns></returns>
        public static bool GetICheckControlValueFromRow(GridViewRow row, string checkboxID)
        {
            ICheckBoxControl chkControl = row.FindControl(checkboxID) as ICheckBoxControl;
            if (chkControl != null)
            {
                return chkControl.Checked;
            }
            return false;
        }

        /// <summary>
        /// Set control value to row
        /// The control must implement ICheckControl interface
        /// </summary>
        /// <param name="row"></param>
        /// <param name="checkboxID"></param>
        /// <param name="value"></param>
        public static void SetICheckControlValueToRow(GridViewRow row, string checkboxID, bool value)
        {
            ICheckBoxControl chkControl = row.FindControl(checkboxID) as ICheckBoxControl;
            if (chkControl != null)
            {
                chkControl.Checked = value;
            }
        }

        /// <summary>
        /// Set control value to row
        /// The control must implement ICheckControl interface
        /// </summary>
        /// <param name="row"></param>
        /// <param name="checkboxID"></param>
        /// <param name="value"></param>
        public static void SetICheckControlValueToRow(GridViewRow row, string checkboxID, bool value, bool readOnly)
        {
            ICheckBoxControl chkControl = row.FindControl(checkboxID) as ICheckBoxControl;
            if (chkControl != null)
            {
                chkControl.Checked = value;
                CheckBox chk = chkControl as CheckBox;
                if (chk != null)
                {
                    chk.Enabled = !readOnly;
                }
            }
        }

        /// <summary>
        /// Get HiddenField value from row
        /// </summary>
        /// <param name="row"></param>
        /// <param name="hiddenFieldID"></param>
        /// <returns></returns>
        public static string GetHiddenFieldValueFromRow(GridViewRow row, string hiddenFieldID)
        {
            HiddenField hfControl = row.FindControl(hiddenFieldID) as HiddenField;
            if (hfControl != null)
            {
                return hfControl.Value;
            }
            return string.Empty;
        }

        /// <summary>
        /// Set Hidden Field value to row
        /// </summary>
        /// <param name="row"></param>
        /// <param name="hiddenFieldID"></param>
        /// <param name="value"></param>
        public static void SetHiddenFieldValueToRow(GridViewRow row, string hiddenFieldID, string value)
        {
            HiddenField hfControl = row.FindControl(hiddenFieldID) as HiddenField;
            if (hfControl != null)
            {
                hfControl.Value = value;
            }
        }

        /// <summary>
        /// Get DropDownList selected value from row
        /// </summary>
        /// <param name="row"></param>
        /// <param name="DropDownListID"></param>
        /// <returns></returns>
        public static string GetDropDownListSelectedValueFromRow(GridViewRow row, string dropDownListID)
        {
            DropDownList ddlControl = row.FindControl(dropDownListID) as DropDownList;
            if (ddlControl != null)
            {
                return ddlControl.SelectedValue;
            }
            return string.Empty;
        }

        /// <summary>
        /// Get javascript alert message
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="addScript"></param>
        /// <returns></returns>
        public static string GetAlertMessage(string msg, bool addScript)
        {
            string script = "<script language=\"javascript\" type=\"text/javascript\">{0}</script>";
            string alert = "alert(\"{0}\");";
            string ligalMessage = msg.Replace("\"", "\\\"");
            alert = string.Format(alert, ligalMessage);
            if (addScript)
            {
                return string.Format(script, alert);
            }
            else
            {
                return alert;
            }
        }

        /// <summary>
        /// Encode script parameter
        /// </summary>
        /// <param name="script"></param>
        /// <returns></returns>
        public static string EncodeScriptParameter(string script)
        {
            return script.Replace("\n", "\\n")
                .Replace("\r", "\\r")
                .Replace("\'", "\\\'")
                .Replace("\"", "\\\"");
        }

        ///// <summary>
        ///// Convert DBPeriod to Special Format
        ///// </summary>
        ///// <param name="dbPeriod"></param>
        ///// <returns>e.g. 08AP6</returns>
        //public static string GetFormatPeriod(string dbPeriod)
        //{
        //    if (dbPeriod.Length != 8 || !dbPeriod.StartsWith("P"))
        //    {
        //        return dbPeriod;
        //    }

        //    decimal period = ConvertHelper.ToDecimal(dbPeriod.Substring(1));
        //    return ResourceManager.GetString(ResourceManager.Title_AccountPeriodKey, GetYear(period).ToString().Substring(2), GetAccountPeriod(period));
        //}

        /// <summary>
        /// Convert Format Period to DB Period
        /// </summary>
        /// <param name="fmtPeriod"></param>
        /// <returns>e.g. P2008004</returns>
        public static string FromFormatPeriodToDBPeriod(string fmtPeriod)
        {
            if (fmtPeriod.Length < 5 || fmtPeriod.Length > 7 || fmtPeriod.IndexOf("AP") < 0)
            {
                return fmtPeriod;
            }

            string[] zeros = new string[] { "00", "0", "" };
            return "P20" + fmtPeriod.Substring(0, 2) + zeros[fmtPeriod.Length - 5] + fmtPeriod.Substring(4);
        }

        private static int GetYear(decimal period)
        {
            return (int)(period / 1000);
        }

        private static int GetAccountPeriod(decimal period)
        {
            return (int)(period - GetYear(period) * 1000);
        }

        public static string GetDBPeriod(decimal period)
        {
            return GetDBPeriod(period, "P");
        }

        /// <summary>
        /// Get the period right next the base period
        /// </summary>
        /// <param name="basePeriod"></param>
        /// <param name="periods"></param>
        /// <returns></returns>
        public static string GetNextBasePeriod(decimal basePeriod, List<decimal> periods)
        {
            for (int i = 0; i < periods.Count; i++)
            {
                if (periods[i] > basePeriod)
                {
                    return GetDBPeriod(periods[i]);
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// Get the period right next the period
        /// </summary>
        /// <param name="basePeriod"></param>
        /// <param name="periods"></param>
        /// <returns></returns>
        public static string GetBindingProperty(decimal basePeriod, decimal curPeriod, List<string> periods, ref bool isSameRow)
        {
            isSameRow = true;
            bool isCurrentPeriodPass = false;
            bool isContainOtherColumn = false;
            for (int i = 0; i < periods.Count; i++)
            {
                if (periods[i].ToUpper().StartsWith("P"))
                {
                    decimal currentPeriod = ConvertHelper.ToDecimal(periods[i].Substring(1));
                    if (currentPeriod == curPeriod)
                    {
                        isCurrentPeriodPass = true;
                    }
                    if (currentPeriod > curPeriod)
                    {
                        isSameRow = true;
                        if (isContainOtherColumn)
                        {
                            return periods[i];
                        }
                        else
                        {
                            return string.Empty;
                        }
                    }
                }
                else if (isCurrentPeriodPass)
                {
                    isContainOtherColumn = true;
                }
            }
            isSameRow = false;
            return GetFirstBindingProperty(basePeriod, periods);
        }

        public static string GetDBPeriod(decimal period, string prefix)
        {
            return prefix + period.ToString();
        }

        /// <summary>
        /// Get the display format of KeyValuePairs
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string DisplayKeyValuePairs<TKey, TValue>(List<KeyValuePair<TKey, TValue>> list)
        {
            StringBuilder builder = new StringBuilder();
            foreach (KeyValuePair<TKey, TValue> pair in list)
            {
                builder.Append(pair.Key.ToString())
                    .Append(": ")
                    .Append(pair.Value.ToString())
                    .Append("    ");
            }
            return builder.ToString();
        }

        public static string GetFirstBindingProperty(decimal basePeriod, List<string> periods)
        {
            foreach (string period in periods)
            {
                if (period.StartsWith("P"))
                {
                    try
                    {
                        decimal value = Convert.ToDecimal(period.Substring(1));
                        if (value > basePeriod)
                        {
                            return period;
                        }
                    }
                    catch (System.Exception)
                    {
                        continue;
                    }
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// Get application path
        /// </summary>
        /// <returns></returns>
        public static string GetApplicationPath()
        {
            //string strServer = "http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToString();
            //string strPort = ":" + Convert.ToString(HttpContext.Current.Request.ServerVariables["SERVER_PORT"]);
            //// Process Route Port Mapping Condition
            //// e.g. Origion port is 8088, the routed port is 80
            ////      then convert strPort to 80
            //if (!HttpContext.Current.Request.Url.OriginalString.Contains(strPort))
            //{
            //    string routedPort = ConfigurationManager.AppSettings[ConstantsManager.RoutedPortKey];
            //    if (string.IsNullOrEmpty(routedPort))
            //    {
            //        strPort = ":80";
            //    }
            //    else
            //    {
            //        strPort = ":" + routedPort.Trim();
            //    }
            //}

            string strRoot = HttpContext.Current.Request.ApplicationPath + "/";
            //if (StringHelper.EqualIgnoreCase(strPort.Trim(), ":80"))
            //{
            //    strPort = "";
            //}
            if (StringHelper.EqualIgnoreCase(strRoot, "//"))
            {
                strRoot = "/";
            }
            //return strServer + strPort + strRoot;
            return strRoot;
        }
    }
}
